package com.canyou.basic;

import com.canyou.api.BaseApiController;
import com.canyou.api.ResponseBO;
import com.canyou.basic.entity.media.MediaVO;
import com.canyou.basic.model.Media;
import com.canyou.basic.service.MediaService;
import com.canyou.enums.ErrorCodeEnum;
import com.canyou.enums.MediaStoreTypeEnum;
import com.canyou.exception.CysBusinessException;
import com.canyou.utils.RequestUtils;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.List;

import static com.canyou.api.ResponseBO.*;

/**
 * <p>
 * 上传文件资源表 前端控制器
 * </p>
 *
 * @author canyou
 * @since 2020-02-13
 */
@ApiSort(1009)
@Api(tags = "文件上传下载")
@RestController
@RequestMapping("/media")
@Slf4j
@Validated
public class MediaController extends BaseApiController {

    @Autowired
    private MediaService mediaService;

    /**
     * 文件上传
     *
     * @param file 上传的文件
     * @return
     * @throws IOException
     */
    @ApiOperation("文件上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "待上传的文件", paramType = "form",
                    dataType = "MultipartFile", required = true),
            @ApiImplicitParam(name = "storeType", paramType = "query", value = "资源存储方式(1.本地存储,2.七牛,3.阿里,4.minio)默认为本地存储",
                    dataType = "int", example = "1", defaultValue = "1")
    })
    @PostMapping("/upload")
    public ResponseBO<Media> upload(
            @NotNull(message = "文件不能为空")
            @RequestPart(value = "file") MultipartFile file,
            @RequestParam(value = "storeType", required = false, defaultValue = "1") Integer storeType) throws IOException {
        MediaStoreTypeEnum mediaStoreTypeEnum = MediaStoreTypeEnum.valueOf(storeType);
        Media media = mediaService.saveFile(file, mediaStoreTypeEnum);
        mediaService.getMediaPath(request, media);
        return ok(media, "上传成功");
    }

    /**
     * 文件下载
     *
     * @param id 文件id
     * @throws IOException
     */
    @ApiOperation(value = "文件下载")
    @ApiImplicitParam(name = "id", paramType = "path", value = "文件资源id",
            dataType = "long", required = true, example = "1")
    @GetMapping("/download/{id}")
    public void download(@NotNull(message = "文件资源id不能为空")
                         @PathVariable(name = "id") Long id) throws IOException {
        Media media = mediaService.getById(id);
        if (media == null) {
            throw new CysBusinessException(ErrorCodeEnum.ILLEGAL, "文件不存在");
        }
        MediaStoreTypeEnum storeTypeEnum = MediaStoreTypeEnum.valueOf(media.getStoreType());
        if (!MediaStoreTypeEnum.LOCAL.equals(storeTypeEnum)) {
            response.sendRedirect(media.getMediaPath());
            return;
        }
        // 文件所在路径
        String filePath = mediaService.getUploadAbsolutePath(media.getMediaPath());
        boolean isMsBrowser = RequestUtils.isMsBrowser(request);
        mediaService.download(response, filePath, media.getOriginalMediaName(), media.getMimeType(), null, isMsBrowser);
    }

    @ApiOperation(value = "根据id集合获取上传文件信息")
    @PostMapping("/get_media_list_info")
    public ResponseBO<List<MediaVO>> getMediaListInfo(@ApiParam(name = "ids", type = "array", value = "文件id集合",
            required = true, examples = @Example(value = @ExampleProperty(value = "[1, 2]")))
                                                      @Valid
                                                      @NotNull(message = "文件id集合不能为空")
                                                      @NotEmpty(message = "至少包含一个文件id")
                                                      @RequestBody List<Long> ids) {
        // 获取带url直接访问路径的上传文件信息
        List<MediaVO> medias = mediaService.getListWithUrlByIds(request, ids);
        if (medias.isEmpty()) {
            return illegal("文件信息不存在");
        }
        return ok(medias);
    }

}
